﻿using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.ServiceLocation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xceed.Wpf.AvalonDock;
using Xceed.Wpf.AvalonDock.Layout.Serialization;

namespace Dataforge.PrismAvalonExtensions
{
  public class SerializationHelper
  {
    public static void Serialize(DockingManager dm, string filename)
    {
      XmlLayoutSerializer s = new XmlLayoutSerializer(dm);
      s.Serialize(filename);
    }

    public static void Deserialize(DockingManager dm, string regionName, string filename)
    {
      FileInfo fi = new FileInfo(filename);
      if (!fi.Exists) return;

      XmlLayoutSerializer s = new XmlLayoutSerializer(dm);
      s.LayoutSerializationCallback += (sender, e) =>
      {
        Type viewType = Type.GetType(e.Model.ContentId);
        if (viewType == null) return;
        IRegionManager rm = ServiceLocator.Current.GetInstance<IRegionManager>();
        object o = ServiceLocator.Current.GetInstance(viewType);
        rm.Regions[regionName].Add(o);
        e.Content = o;
      };
      s.Deserialize(filename);
    }
  }
}
